package com.linjm.gmallpassport.controller;

import com.linjm.bean.UserInfo;
import com.linjm.gmallpassport.util.JwtUtil;
import com.linjm.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class PassportController {

    @Value("${token.key}")
    private String key;

    @DubboReference
    private UserService userService;

    @RequestMapping("index")
    public String index(HttpServletRequest request ){
        // 获取originUrl
        String originUrl = request.getParameter("originUrl");
        // 保存originUrl
        request.setAttribute("originUrl",originUrl);
        return "index";
    }

    @RequestMapping("login")
    @ResponseBody
    public String login(UserInfo userInfo,HttpServletRequest request){
        String salt = request.getHeader("X-forwarded-for");
        //调用登陆方法
        UserInfo info = userService.login(userInfo);
        if(info!=null){
            //制作token
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId",info.getId());
            map.put("nickName",info.getNickName());
            return JwtUtil.encode(key,map, salt);
        }else {
            return "fail";
        }
    }

    @RequestMapping("verify")
    @ResponseBody
    public String verify(HttpServletRequest request){
        //1.	获取服务器的Ip，token
//        2.	key+ip ,解密token 得到用户的信息 userId,nickName
//        3.	判断用户是否登录：key=user:userId:info  value=userInfo
//        4.	userInfo!=null true success; false fail;
//        String salt = request.getHeader("X-forwarded-for");
       // String salt = request.getParameter("X-forwarded-for");
        String token = request.getParameter("token");
        String salt = request.getParameter("salt");
        Map<String, Object> map = JwtUtil.decode(token, key, salt);
        if(map!=null){
            String userId = (String) map.get("userId");
            UserInfo userInfo=userService.verify(userId);
            if (userInfo!=null){
                return "success";
            }
        }
        return "fail";

    }


}

